import grails.converters.*

class ShoppingCartController {

	String sometext
	String shoppingCartControllerPath = "/PictureCentral/shoppingCart/"
	String shoppingCartImagePath = "/PictureCentral/images/shoppingcart/"
	String currencySign = '$'
	
    def index = {
    	redirect(action:view)
    }

	def add = {
		if (session.userCart == null) {
			session.userCart = ""
		}
		session.userCart += params.itemID + ","
		checkForSameItem()
		redirect(action:view)
	}
	
	def checkForSameItem = {
		def charSeparator
		def lastChar
		def row = session.userCart.split(",")
		lastChar = "null"
		row.sort()
		session.userCart = ""
		row.each {
			if (it == lastChar) {
				it = ""
				charSeparator = ""
			}
			else {
				charSeparator = ","
			}
			session.userCart += it + charSeparator
			lastChar = it
		}
	}
	
	def remove = {
		def charSeparator
		def row = session.userCart.split(",")
		session.userCart = ""
		row.each {
			if (it == params.itemID) {
				it = ""
				charSeparator = ""
			}
			else {
				charSeparator = ","
			}
			session.userCart += it + charSeparator
		}
		redirect(action:view)
	}
	
	def view = {
		if(session.authenticatedUser == null) {
			redirect(controller:'authentication', action:'index')
		}
		if (session.userCart == null) {
			session.userCart = ""
		}
		def row = session.userCart.split(",")
		def recordSet
		def record
		def pictureInstance
		session.totalPrice = 0
		recordSet = []
		row.each {
			if (it) {
				pictureInstance = Picture.get(it)
				if (pictureInstance) {
					record = [:]
					record.id = pictureInstance.id
					record.name = pictureInstance.name
					record.price = pictureInstance.price
					record.thumbnailPath = pictureInstance.thumbnailPath
					recordSet.add(record)
					session.totalPrice += pictureInstance.price
				}
			}
			else {
				flash.message = "Shopping cart is empty."
			}
		}
		[currencySign:currencySign, shoppingCartItemsList:recordSet]
	}
	
    def clear = {
       	session.userCart = ""
       	session.totalPrice = 0
       	flash.message = "Shopping cart has been cleared."
       	redirect(action:view)
    }

    def login = {
		if(session.authenticatedUser == null) {
			redirect(controller:'authentication', action:'index')
		}
    }

    def logout = {
		if(session.authenticatedUser == null) {
			redirect(controller:'authentication', action:'index')
		}
    }
	
	def saveOrder = {
		def pictureInstance
		def orderID
		def userOrder
		def OrderSaveSuccess = false
		def errorMsg = "";
			def row = session.userCart.split(",")
			orderID = System.currentTimeMillis().toString() + "-" + session.getId()
			userOrder = new UserOrder()
			userOrder.orderID = orderID
			userOrder.login = session.authenticatedUser.login
    	    def AuthenticationService authenticationService = new AuthenticationService()
    	    userOrder.user = authenticationService.getAuthenticationUser(session.authenticatedUser) 
			userOrder.totalPrice = session.totalPrice
			userOrder.name = params.name
			userOrder.address = params.address
			userOrder.city = params.city
			userOrder.state = params.state
			userOrder.zipcode = params.zipcode
			userOrder.paymentDetail = params.paymentDetail //"paypal"
			userOrder.remoteIPAddress = request.getRemoteAddr()
			userOrder.createdOn = new Date()
			userOrder.status = "1"
			row.each {
				pictureInstance = Picture.get(it)
				if (pictureInstance) {
					userOrder.addToPictures(pictureInstance)
				}
			}
			if(!userOrder.hasErrors() && userOrder.save()) {
				OrderSaveSuccess = true
			}
			else {
				errorMsg = "Cannot save order " + orderID + " for session id: " + session.getId()
			}

		def response = [];
		if (OrderSaveSuccess) {
			session.userCart = ""
			session.totalPrice = 0
			def url = "/PictureCentral/shoppingCart/listOrders?orderID="+orderID
			response = [success:true, url:url]
		} else {
			response = [success:false,  errors: errorMsg]
		}
		render response as JSON
	}
	
	def listOrders = {
		// navigation only	
		if(session.authenticatedUser == null) {
          	redirect(controller:'authentication',action:'index')	
        }
	}
	
	def listOfOrders = {
		def userOrders
		def title = ''
		if (params.orderID) {
			userOrders = UserOrder.findAllWhere(orderID:params.orderID)
			title = 'Order ' + params.orderID
		} 
		else {
	    	def AuthenticationService authenticationService = new AuthenticationService()
	    	def user = authenticationService.getAuthenticationUser(session.authenticatedUser)
	    	userOrders = UserOrder.findAllWhere(user: user)
			//userOrder = UserOrder.findAllWhere(login: session.authenticatedUser.login)
			title = 'My Orders'
		}
		def response = [row: userOrders, title: title]
		render response as JSON
	}
	
	def orderedPictures = {
		// navigation only	
		if(session.authenticatedUser == null) {
	       	redirect(controller:'authentication',action:'index')	
	    }			
	}
	
	def download = {
		def pictureInstance = Picture.get(params.id)
		if (pictureInstance) {
			String imagePath = pictureInstance.getLongPath(pictureInstance.imagePath)
			def file = new File(imagePath)    
			response.setHeader("Content-disposition", "filename=" + URLEncoder.encode(pictureInstance.name + ".jpg"))
			response.setContentType("application/octet-stream")
			response.outputStream << file.newInputStream()
		}
	}
	
	def userOrderedPictures = {
		def userOrders
		def title = 'My Downloads'
	   	def AuthenticationService authenticationService = new AuthenticationService()
	   	def user = authenticationService.getAuthenticationUser(session.authenticatedUser)
		userOrders = UserOrder.findAllWhere(user: user)
		def pictureList = []
		// not very efficient
		for(UserOrder order:userOrders) {
			pictureList.addAll(order.pictures)
		}
		def response = [row: pictureList, title: title]
		render response as JSON			
	}

	def listOrderLine = {
		def orderLine
		if (params.orderID) {
			orderLine = OrderLine.findAllWhere(orderID:params.orderID)
		}
		[row: orderLine]
	}

	def deleteOrder = {
		//def userOrder = UserOrder.findAllWhere(orderID:params.orderID)
		//def orderLine = OrderLine.findAllWhere(orderID:params.orderID)
	}

	def printText = {
		if (!sometext) {
			sometext = ""
		}
		response.outputStream << sometext
	}
}